import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:get/get.dart';

class DioDemoLoadMore extends StatefulWidget {
  const DioDemoLoadMore({Key? key}) : super(key: key);

  @override
  _DioDemoLoadMoreState createState() => _DioDemoLoadMoreState();
}

class _DioDemoLoadMoreState extends State<DioDemoLoadMore> {
  final _scrollController = ScrollController();
  List _list = [];
  int page = 0;
  bool hasMoreData = true;

  _getData() async {
    page++;
    var apiUrl =
        "https://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=$page";

    var response = await Dio().get(apiUrl);

    var res = json.decode(response.data)["result"];

    setState(() {
      _list.addAll(res);
    });

    if (res.length < 20) {
      setState(() {
        hasMoreData = false;
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getData();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 20) {
        if (hasMoreData) {
          _getData();
        }
      }
    });
  }

  // 自定义组件
  Widget _progressIndicator() {
    if (hasMoreData) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    } else {
      return const Text("---我是有底线的---");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("上拉 & 下拉"),
      ),
      body: _list.isNotEmpty
          ? RefreshIndicator(
              // child: ListView(
              //   controller: _scrollController,
              //   children: _list.map((value) {
              //     return ListTile(title: Text("${value["title"]}"));
              //   }).toList(),
              // ),
              child: ListView.builder(
                  controller: _scrollController,
                  itemCount: _list.length,
                  itemBuilder: (context, index) {
                    if (index == _list.length - 1) {
                      return Column(
                        children: [
                          SizedBox(
                            height: 60,
                            child: ListTile(
                              title: Text("${_list[index]["title"]}"),
                              onTap: () {
                                Get.toNamed("/diodemonewsdetail",
                                    arguments: {"aid": _list[index]["aid"]});
                              },
                            ),
                          ),
                          const Divider(),
                          _progressIndicator()
                        ],
                      );
                    } else {
                      return SizedBox(
                        height: 60,
                        child: ListTile(
                          title: Text("${_list[index]["title"]}"),
                          onTap: () {
                            Get.toNamed("/diodemonewsdetail",
                                arguments: {"aid": _list[index]["aid"]});
                          },
                        ),
                      );
                    }
                  }),
              onRefresh: () async {
                page = 0;
                await _getData();
              })
          : _progressIndicator(),
    );
  }
}
